package org.fitweb.fixture;

import org.openqa.selenium.RenderedWebElement;
import org.openqa.selenium.WebElement;

import java.awt.*;

public enum ElementState {
    visible {
        @Override
        public boolean appliesTo(WebElement element) {
            if (element == null) return false;

            RenderedWebElement renderedWebElement = (RenderedWebElement) element;
            Point location = renderedWebElement.getLocation();

            // TODO - CAS - Nov 24, 2010 - Bug in WebDriver or HtmlUnit: location and size of element are always the same. We will assume anything > 10 pixels offscreen is invisble.
            boolean horizontallyVisible = location.getX() > -10;
            boolean verticallyVisible = location.getY() > -10;


            return !hiddenByStyles(renderedWebElement) && renderedWebElement.isDisplayed() && horizontallyVisible && verticallyVisible;
        }

        // TODO - CAS - Nov 29, 2010 - Another bug in WebDriver or HtmlUnit: isDisplayed() doesn't work for css applied through classes, although it works for style=""
        private boolean hiddenByStyles(RenderedWebElement element) {
            return "none".equalsIgnoreCase(css(element, "display")) || "hidden".equalsIgnoreCase(css(element, "visibility"));
        }
    };

    private static String css(RenderedWebElement renderedWebElement, String propertyName) {
        return renderedWebElement.getValueOfCssProperty(propertyName);
    }

    public static ElementState called(String stateName) {
        return ElementState.valueOf(stateName.toLowerCase());
    }

    public abstract boolean appliesTo(WebElement element);
}
